<?php

// spidertest.php
// Michael Baker
// 2010.08.22
//
// Test AJAX functionality

// This does not work in IE currently - it has trouble with the http_request.send(null); line.

?>
<html>
<head>
<title>AJAX Test</title>
<script type="text/javascript" language="javascript">
  var http_request = false;
  function makeRequest(url, parameters) {
    http_request = false;
    if (window.XMLHttpRequest) { //Mozilla, Safari, ...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
        http_request.overrideMimeType('text/xml');
      }
    }
    else if (window.ActiveXObject) { // IE
      try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e) {
        try {
          http_request = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch (e) {}
      }
    }
    if (!http_request) {
      alert('Cannot create XMLHTTP instance');
      return false;
    }

    http_request.onreadystatechange = alertContents;
    http_request.open('GET', url + parameters, true);
    http_request.send(null);
  }

  function alertContents() {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        var xmldoc = http_request.responseXML;
        var root = xmldoc.getElementsByTagName('root').item(0);

        var nodes = root.getElementsByTagName('nodes').item(0);
        for (var i = 0; i < nodes.getElementsByTagName('node').length; i++) {
          var nObj = nodes.getElementsByTagName('node').item(i);

          var arr = new Array(2);
          
          // Retrieve the data
          var lname = nObj.getElementsByTagName('lname')[0];
          var addr  = nObj.getElementsByTagName('addr')[0];
          
          arr[0] = lname.textContent;
          arr[1] = addr.textContent;

          addrow("test", arr);
        }

      }
    }
  }

  function do_xml() {
    // clear the table first
    var tbl = document.getElementById('test');
    while (tbl.rows.length > 1) {
      tbl.deleteRow(tbl.rows.length - 1);
    }

    // retrieve IP from user input
    var ip = document.getElementById('ip').value;

    // perform xml request
    makeRequest('fetch_node_xml.php', '?ip=' + ip);
  }

  function addrow(tablename, arr) {
    var tbl = document.getElementById(tablename);
    var lastRow = tbl.rows.length;
    var row = tbl.insertRow(lastRow);

    for (var r = 0; r < arr.length; r++) {
      var cell = row.insertCell(r);
      cell.innerHTML = arr[r];
    }
  }

</script>
<body>
<h1>XML/JavaScript-powered nodetable spider test</h1><hr />
Enter any MA IP to spider: <input id="ip" value="1.133.58.2" />
<input type="button" name="button" value="POPULATE" onclick="javascript:do_xml();">
<table id="test" width="600px" border="1">
<tr><td><strong>Node Name</strong></td><td><strong>Node Address</strong></td></tr>
</table>
<hr />Michael Baker
</body>
</html>

